<template>
  <RenderLayout v-if="!!designer.widget" :designer="designer" />
</template>

<script setup lang="ts" name="MicroRender">
import { watch } from "vue";
import RenderLayout from "./RenderLayout.vue";
import microPageApi from "@/views/micro/page/api";
import microEntityApi from "@/views/micro/entity/api";
import microAppApi from "@/views/micro/app/api";
const props = defineProps({
  pageId: {
    type: Number
  },
  designer: {
    type: Object
  }
});
const selectPageWidget = () => {
  if (props.pageId) {
    const pageList = props.designer!.global.pageList;
    for (const page of pageList) {
      if (page.id === props.pageId) {
        const pageJson = page.pageJson;
        props.designer!.widget = pageJson;
        break;
      }
    }
  }
};
watch(
  () => props.designer!.global.appId,
  async appId => {
    if (appId) {
      if (props.designer!.global.pageList.length > 0) {
        selectPageWidget();
        return;
      }
      const microApp = await microAppApi.query(appId);
      if (microApp) {
        props.designer!.global.appId = microApp.id;
        props.designer!.global.appName = microApp.appName;
        props.designer!.global.pageType = microApp.pageType;
        props.designer!.global.entityId = microApp.entityId;
        props.designer!.global.pkFields = await microEntityApi.getPkFields({ id: microApp.entityId });
      }
      const res = await microPageApi.list({ appId });
      const pageList = res.map(r => {
        const pageJson = r.pageJson;
        if (pageJson) {
          r.pageJson = JSON.parse(r.pageJson);
        }
        return r;
      });
      props.designer!.global.pageList = pageList;
    } else {
      props.designer!.global.entityId = null;
      props.designer!.global.pageList = [];
    }
    selectPageWidget();
  },
  { immediate: true }
);

watch(
  () => props.pageId,
  async pageId => {
    if (pageId) {
      const pageList = props.designer!.global.pageList;
      if (pageList.length === 0) {
        const appId = await microPageApi.getAppId({ id: pageId });
        if (appId) {
          props.designer!.global.appId = appId;
        }
      } else {
        selectPageWidget();
      }
    }
  },
  {
    immediate: true
  }
);
</script>

<style lang="scss"></style>
